package com.lvfuyang.commonproject.filter;

import java.io.IOException;
import java.util.UUID;

import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import org.slf4j.MDC;

/**
 * @description 过滤器，每次请求设置日志唯一追踪ID
 */
public class LogMDCFilter implements Filter {

    public static final String UNIQUE_ID_NAME = "traceId";

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
                         FilterChain filterChain) throws IOException, ServletException {
        // 生成并设置traceId
        String traceId = UUID.randomUUID().toString().replace("-", "");
        MDC.put(UNIQUE_ID_NAME, traceId);

        try {
            // 继续执行过滤链
            filterChain.doFilter(servletRequest, servletResponse);
        } finally {
            // 确保在finally块中清理MDC，避免内存泄漏
            MDC.remove(UNIQUE_ID_NAME);
        }
    }
}